<?php
require_once 'IHandler.class.php';
require_once ROOT_PATH . 'lib/upload/Upload.class.php';
/**
 * <h2>文件上传处理</h2>
 */
class UploadHandler implements IHandler {
	/**
	 *
	 * @var Logger
	 */
	private $_logger;
	public function __construct() {
		Logger::configure ( ROOT_PATH . 'config/log_config.xml' );
		$this->_logger = Logger::getLogger ( __CLASS__ );
	}
	
	/**
	 * <h2>处理Ajax上传</h2>
	 *
	 * @see IHandler::handle()
	 */
	public function handle() {
		$ret = NULL;
		$request = new Request ();
		$form_seed = $request->getRequest ( FORM_HASH );
		if (empty ( $form_seed )) {
			$ret ['success'] = false;
			echo json_encode ( $ret );
			return;
		}
		$sessMgr = SessionManager::getSingleton ();
		// TODO 权限检测
		$upload = new Upload ( $_FILES ['qqfile'], 'zh_CN' );
		try {
			if (! $upload->uploaded) {
				throw new ExceptionEx ( "Invalid upload file [" . __CLASS__ . "] [" . __LINE__ . "]" );
			}
			if (! $upload->file_is_image) {
				throw new ExceptionEx ( "Upload File is Not Image [" . __CLASS__ . "] [" . __LINE__ . "]" );
			}
			// 构造保存路径
			$time = time ();
			$year = date ( "Y", $time );
			date ( "m", $time ) == 12 && date ( "W", $time ) == 1 && $year ++;
			$savePath = $year . '/' . date ( 'W', $time ) . '/' . date ( 'w', $time ) . '/'; // 基路径
			                                                                                 // (按照年份/周/星期x)
			$uniqName = uniqid ();
			
			$upload->file_new_name_body = $uniqName; // 设置保存的文件名儿
			$upload->file_max_size = UPLOAD_MAX_SIZE;
			
			// 保存
			$upload->process ( UPLOAD_PATH . $savePath );
			
			if (! $upload->processed) {
				// response failed
				$ret ['failed'] = 'failed';
				throw new ExceptionEx ( "Process upload file failed [" . __CLASS__ . "] [" . __LINE__ . "]" );
			}
			
			$conn = DBHelper::getDB ( false );
			$query = "INSERT INTO attachments SET ts_upload=" . time ();
			$query .= ",mime='" . $upload->file_src_mime . "'";
			$query .= ",uniqname='" . $savePath . $upload->file_dst_name . "'";
			// $query .= ",filename='" . $upload->file_src_name . "'";
			$query .= ",filename='" . $request->getGet ( 'qqfilename' ) . "'";
			$this->_logger->debug ( $query );
			$attachId = $conn->insert ( $query );
			
			// 生成縮略圖
			$upload->image_resize = true;
			$thumb_x = 128;
			$upload->image_x = $thumb_x;
			$upload->image_y = round ( $upload->image_src_y * ($thumb_x / $upload->image_src_x) );
			$upload->file_new_name_body = $uniqName . THUMB_SUFFIX;
			$upload->process ( UPLOAD_PATH . $savePath );
			
			$img_data = file_get_contents ( $upload->file_dst_pathname );
			// response
			$ret ['success'] = true;
			$ret ['id'] = $attachId;
			$ret ['thumbnail'] = "data:{$upload->file_src_mime};base64,";
			$ret ['thumbnail'] .= base64_encode ( $img_data );
			
			// 存储到回话中
			$aList = $sessMgr->getAttribute ( 'a_' . $form_seed );
			if (empty ( $aList )) {
				$aList = array ();
			}
			array_push ( $aList, $attachId );
			$sessMgr->setAttribute ( 'a_' . $form_seed, $aList );
		} catch ( ExceptionEx $e ) {
			$this->_logger->error ( "process upload file failed [" . __CLASS__ . "] [" . __LINE__ . "]" );
		} catch ( Exception $e ) {
			$this->_logger->error ( "Save attachment info failed ]" . __CLASS__ . "] [" . __LINE__ . "]" );
		}
		
		$upload->clean (); // 清理臨時文件
		header ( "Content-Type:text/html" );
		header ( "Charset:utf-8" );
		echo json_encode ( $ret );
	}
}